<script setup lang="ts">
import { showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
// 控制头像弹窗显隐
const showAvatarSheet = ref(false)

// 弹窗选项
const actions = [{ name: '拍照' }, { name: '相册' }]
// 取消选项
const onCancel = () => {
  showToast('取消')
}

// ----------- 修改头像方法 -----------

// 选择不同选项时触发
const onSelect = async (action: ActionSheetAction, index: number) => {
  // console.log(action, index)
  if (index === 0) {
    // console.log('拍照')
    const res = await mk.pickerCamera()
    // console.log('拍照',res)
  } else if (index === 1) {
    // console.log('去相册')
    const res = await mk.pickerPhoto()
    // console.log('相册', res)
    // --- 1. base 转 二进制 ----------
    const img = b64toBlob(res, 'img/jpeg')
    try {
      // --- 2. 关闭头像选择弹层 --------------
      showAvatarSheet.value = false
      // --- 3. 创建一个转载数据的 FormData 对象 -------------------
      const fd = new FormData()
      // --- 4. 追加数据 ------------
      fd.append('file', img, Date.now() + '.jpeg')
      console.log('222')
      // --- 5. 调用上传接口， 根据接口文档设置地址和方法， FormData 设置到参数2 即可
      const uploadRes = await request.post<MkResponse<{ avatar: string }>>(
        'member/profile/avatar',
        fd,
      )
      console.log('111')
      // --- 6. 修改页面显示 , post请求返回头像地址---------
      profile.value.avatar = uploadRes.data.result.avatar
      // --- 7. 获取保存在鸿蒙缓存中的用户信息
      const user = mk.queryUser()
      // --- 8. 修改用户信息头像 为刚刚上传的头像 ---
      user.avatar = uploadRes.data.result.avatar
      // --- 9. 更新鸿蒙端的用户信息头像数据 ---
      mk.updateUser(user)
      // --- 10. 提示用户修改成功 ---
      showToast('上传成功')
    } catch (e) {
      showToast('上传失败')
      console.log(e)
    }
  }
}

// 控制生日弹层相关 ---------------------
const showBirthday = ref(false)
const currentDate = ref(['2021', '01', '01'])
const minDate = ref(new Date(1999, 0, 1))
const maxDate = ref(new Date(2025, 9, 1))
const onBirthdayConfirm = () => {
  // console.log(currentDate.value)
  profile.value.birthday = currentDate.value.join('-')
  showBirthday.value = false
}

// --------- 省市区的弹层相关 ---------------------------
/**
 * 1. 省市区的选项组件
 * 2. 省市区的数据
 * 3. 点击取消关闭
 * 4. 点击确认获取数据 + 关闭
 */
import { areaList } from '@vant/area-data'
import axios from 'axios'
import { request } from '@/apis'
import b64toBlob from 'b64-to-blob'

const showArea = ref(false)
const onAreaConfirm = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  showArea.value = false
  console.log(selectedValues)
  // console.log(selectedOptions)
  // console.log(selectedIndexes)
  // profile.value.fullLocation = selectedOptions[0].text + ' '+ selectedOptions[1].text + ' ' +selectedOptions[2].text
  const arr = selectedOptions.map((item) => {
    return item.text
  })
  profile.value.fullLocation = arr.join(' ')
  profile.value.cityCode = selectedValues[1]
  profile.value.provinceCode = selectedValues[0]
  profile.value.countyCode = selectedValues[2]
}

// --------- 职业的弹层相关 ---------------------------
const showJob = ref(false)

const columns = [
  { text: '警察', value: '警察' },
  { text: '程序员', value: '程序员' },
  { text: '医生', value: '医生' },
  { text: '厨师', value: '厨师' },
  { text: '老板', value: '老板' },
  { text: '主播', value: '主播' },
]

const onConfirm = ({ selectedValues }) => {
  // showToast(`当前值: ${selectedValues.join(',')}`);
  showJob.value = false
  profile.value.profession = selectedValues.join('')
}

const selectJob = ref<string[]>([])

// ----------- 发送请求获取用户数据 ----------

const profile = ref({} as ProfileInfo)
onMounted(async () => {
  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  console.log(res.data.result)
  profile.value = res.data.result
  currentDate.value = profile.value.birthday.split('-')
  selectJob.value = [profile.value.profession]
})

// ------------- 保存资料 ----------
import { showLoadingToast } from 'vant'

const saveUser = async () => {
  // console.log(res)
  showLoadingToast({
    message: '加载中...',
  })
  const res = await request.put<MkResponse<ProfileInfo>>('/member/profile', profile.value)

  mk.updateUser(res.data.result)
  showToast({ message: '修改成功' })
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        placeholder="请选择日期"
        @click="showBirthday = true"
        v-model="profile.birthday"
      ></van-field>
      <van-field
        label="所在地"
        readonly
        placeholder="请选择所在地"
        @click="showArea = true"
        v-model="profile.fullLocation"
      ></van-field>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        @click="showJob = true"
        v-model="profile.profession"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="saveUser"> 保存资料 </van-button>
    </div>
  </div>

  <!-- 生日弹层组件 -->
  <van-popup v-model:show="showBirthday" position="bottom" :style="{ padding: '50px' }"
    ><van-date-picker
      v-model="currentDate"
      title="选择日期"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="onBirthdayConfirm"
      @cancel="showBirthday = false"
  /></van-popup>

  <!-- 省市区弹层组件 -->
  <van-popup v-model:show="showArea" position="bottom" :style="{ padding: '50px' }">
    <van-area
      title="省市区选择"
      :area-list="areaList"
      @cancel="showArea = false"
      @confirm="onAreaConfirm"
    />
  </van-popup>

  <!-- 职业弹层组件 -->
  <van-popup v-model:show="showJob" position="bottom" :style="{ padding: '50px' }">
    <van-picker
      v-model="selectJob"
      title="选择职业"
      :columns="columns"
      @confirm="onConfirm"
      @cancel="showJob = false"
    />
  </van-popup>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
